﻿Imports System.IO
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Collections
Imports System.Data
Imports System.Configuration
Imports Ckeditor_Util
Imports Ckeditor_ImageMedia

Partial Public Class LinkBrowser
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsPostBack Then
            BindDirectoryList()
            ChangeDirectory(Nothing, Nothing)

            NewDirectoryButton.OnClientClick = "var name = prompt('Enter name of folder:'); if (name == null || name == '') return false; document.getElementById('" + NewDirectoryName.ClientID & "').value = name;"
        End If

        Page.ClientScript.RegisterStartupScript(Me.[GetType](), "FocusImageList", "window.setTimeout(""document.getElementById('" + ImageList.ClientID & "').focus();"", 1);", True)
    End Sub

    Protected Sub BindDirectoryList()
        LinkFolder = ""
        Dim directories As String() = Directory.GetDirectories(FileLinkFolder)
        directories = Array.ConvertAll(Of String, String)(directories, Function(directory__1 As String) directory__1.Substring(directory__1.LastIndexOf("\"c) + 1))
        DirectoryList.DataSource = directories
        DirectoryList.DataBind()
        DirectoryList.Items.Insert(0, "Root")
    End Sub

    Protected Sub ChangeDirectory(ByVal sender As Object, ByVal e As EventArgs)
        DeleteDirectoryButton.Enabled = (DirectoryList.SelectedIndex <> 0)
        LinkFolder = If((DirectoryList.SelectedIndex = 0), "", DirectoryList.SelectedValue + "/")
        SearchTerms.Text = ""
        BindImageList()
        SelectImage(Nothing, Nothing)
    End Sub

    Protected Sub DeleteFolder(ByVal sender As Object, ByVal e As EventArgs)
        Directory.Delete(FileLinkFolder, True)
        BindDirectoryList()
        ChangeDirectory(Nothing, Nothing)
    End Sub

    Protected Sub CreateFolder(ByVal sender As Object, ByVal e As EventArgs)
        Dim name As String = UniqueDirectory(NewDirectoryName.Value)
        Directory.CreateDirectory(FileLinkFolderRoot & name)
        BindDirectoryList()
        DirectoryList.SelectedValue = name
        ChangeDirectory(Nothing, Nothing)
    End Sub

    Protected Sub BindImageList()
        ImageList.Items.Clear()
        Dim files As String() = Directory.GetFiles(FileLinkFolder, "*" & SearchTerms.Text.Replace(" ", "*") & "*")

        For Each file As String In files
            ImageList.Items.Add(file.Substring(file.LastIndexOf("\"c) + 1))
        Next

        If files.Length > 0 Then
            ImageList.SelectedIndex = 0
        End If
    End Sub

    Protected Sub Search(ByVal sender As Object, ByVal e As EventArgs)
        BindImageList()
    End Sub

    Protected Sub SelectImage(ByVal sender As Object, ByVal e As EventArgs)
        Dim pos As Integer = ImageList.SelectedValue.LastIndexOf("."c)
        If pos = -1 Then
            Return
        End If
        RenameImageButton.OnClientClick = ("var name = prompt('Enter new filename:','" & ImageList.SelectedValue.Substring(0, pos) & "'); if (name == null || name == '') return false; document.getElementById('") + NewImageName.ClientID & "').value = name + '" & ImageList.SelectedValue.Substring(pos) & "';"

        Dim link As String = LinkFolder + ImageList.SelectedValue
        OkButton.OnClientClick = "window.top.opener.CKEDITOR.dialog.getCurrent().setValueOf('info', 'url', encodeURI('" & link & "')); window.top.close(); window.top.opener.focus();"
    End Sub

    Protected Sub RenameImage(ByVal sender As Object, ByVal e As EventArgs)
        Dim filename As String = UniqueFilename(NewImageName.Value)
        File.Move(FileLinkFolder + ImageList.SelectedValue, FileLinkFolder & filename)
        BindImageList()
        ImageList.SelectedValue = filename
        SelectImage(Nothing, Nothing)
    End Sub

    Protected Sub DeleteImage(ByVal sender As Object, ByVal e As EventArgs)
        File.Delete(FileLinkFolder + ImageList.SelectedValue)
        BindImageList()
        SelectImage(Nothing, Nothing)
    End Sub

    Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
        Dim filename As String = UniqueFilename(UploadedImageFile.FileName)
        UploadedImageFile.SaveAs(FileLinkFolder & filename)

        BindImageList()
        ImageList.SelectedValue = filename
        SelectImage(Nothing, Nothing)
    End Sub

    Protected Sub Clear(ByVal sender As Object, ByVal e As EventArgs)
        Session.Remove("viewstate")
    End Sub

    Protected Sub SelectPage(ByVal sender As Object, ByVal e As EventArgs)
        OkButton.OnClientClick = ("window.top.opener.SetUrl(encodeURI('" & FileLinkFolder) + ImageList.SelectedValue & "')); window.top.close(); window.top.opener.focus();"
    End Sub

    'util methods
    Protected Function UniqueFilename(ByVal filename As String) As String
        Dim newfilename As String = filename

        Dim i As Integer = 1
        While File.Exists(FileLinkFolder & newfilename)
            newfilename = filename.Insert(filename.LastIndexOf("."c), "(" & i & ")")
            i += 1
        End While

        Return newfilename
    End Function

    Protected Function UniqueDirectory(ByVal directoryname As String) As String
        Dim newdirectoryname As String = directoryname

        Dim i As Integer = 1
        While Directory.Exists(FileLinkFolderRoot & newdirectoryname)
            newdirectoryname = directoryname & "(" & i & ")"
            i += 1
        End While

        Return newdirectoryname
    End Function

    'properties
    Protected ReadOnly Property LinkFolderRoot() As String
        Get
            Return ResolveUrl(ConfigurationManager.AppSettings("FilesRoot"))
        End Get
    End Property

    Protected ReadOnly Property FileLinkFolderRoot() As String
        Get
            Return Server.MapPath(LinkFolderRoot)
        End Get
    End Property

    Private Property LinkFolder() As String
        Get
            Return LinkFolderRoot & Convert.ToString(ViewState("folder"))
        End Get
        Set(ByVal value As String)
            ViewState("folder") = value
        End Set
    End Property

    Private ReadOnly Property FileLinkFolder() As String
        Get
            If ViewState("folder") IsNot Nothing Then
                Return FileLinkFolderRoot & ViewState("folder").ToString().Replace("/", "\")
            End If

            Return FileLinkFolderRoot
        End Get
    End Property
End Class